﻿namespace EyeOpen.Mvc
{
	using System.Web.Mvc;
	using System.Web.Routing;
	using EyeOpen.Data;

	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterGlobalFilters(GlobalFilterCollection filters)
		{
			filters.Add(new HandleErrorAttribute());
		}

		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
			routes.IgnoreRoute("favicon.ico");

			routes.MapRoute(
				"Backend",
				"private/{controller}/{action}/{id}",
				new { controller = "BackEnd", action = "Index", id = UrlParameter.Optional });

			routes.MapRoute(
				"Account",
				"Acount/{action}/{id}",
				new { controller = "Account", action = "Index", id = UrlParameter.Optional });

			routes.MapRoute(
				"Default",
				"{language}/{*path}",
				new { controller = "FrontEnd", action = "Index", id = UrlParameter.Optional });

			routes.MapRoute(
				"Root",
				string.Empty,
				new { controller = "FrontEnd", action = "Index", id = UrlParameter.Optional });
		}

		protected void Application_Start()
		{
			CreateDataBaseIfNotExists();

			AreaRegistration.RegisterAllAreas();

			RegisterGlobalFilters(GlobalFilters.Filters);
			RegisterRoutes(RouteTable.Routes);
		}

		private void CreateDataBaseIfNotExists()
		{
			using (var dbContext = new WebSiteDbContext("WebSiteConnection"))
			{
				if (dbContext.Database.Exists())
				{
					return;
				}

				dbContext.Database.CreateIfNotExists();
				new WebSiteDbPopulator().Populate(dbContext);
				dbContext.SaveChanges();
			}
		}
	}
}